//        1.可缓存
//   因为纯函数对相同的输入始终有相同的结果,所以可以把纯函数的结果缓存起来

//记忆函数(当结果相同，只调用一次)
const _ = require("lodash");

function getArea(r) {
  console.log("再次调用");
  return Math.PI * r * r;
}

let getAreaWithMemory = _.memoize(getArea);
console.log(getAreaWithMemory(4)); //50.26548245743669
console.log(getAreaWithMemory(4)); //50.26548245743669
console.log(getAreaWithMemory(4)); //50.26548245743669

//模拟momeize记忆函数方法

function memoize(fn) {
  let cache = {};
  return function () {
    //   先获取参数
    let key = JSON.stringify(arguments);
    //判断有没有缓存结果，有的话取结果，没有的话执行函数
    cache[key] = cache[key] || fn.apply(fn, arguments);
    console.log(cache);
    return cache[key];
  };
}
let getAreaWithMemory1 = memoize(getArea);
console.log(getAreaWithMemory1(4)); //50.26548245743669
console.log(getAreaWithMemory1(4)); //50.26548245743669
console.log(getAreaWithMemory1(4)); //50.26548245743669
